var mixers = [],
    camera, scene, renderer, controls;
var clock = new THREE.Clock;
//房间信息
var roomList = {};
var doorList = null;
var zlVec =[1,0,0];//走廊的方向

//监控信息
var cameraList = [];
//动作
var actionList = [{
    peopleId: 1,
    roomIds: ["JDS-1", "DCRSJC-1"],
    info: "嫌疑人1，\n时间：2018,6,24",
}];
//人物移动状态
var moveAnimat = {
        finish: true, //结束
        curPos: null, //当前位置,
        endPos: null, //结束位置,
        path: [],
        pathNode: null, //路径节点
        curIndex: 0, //当前关键点
        model: null, //模型
        speed: 3, //移动步长
        arrowNode: null, //方向节点
        animations: null,
    }
    //往场景中添加监控
function addCameras(camModel) {
    cameraList.forEach(function(cam) {
        //createCameraBox(cam.pos,cam.attributes);
        var camObj = camModel.clone();
        camObj.position.set(cam.pos.x, cam.pos.y, cam.pos.z);
        if (cam.rot) {
            camObj.rotation.set(cam.rot.x, cam.rot.y, cam.rot.z);
        }
        camObj.attributes = cam.attributes;
        scene.add(camObj);
    })
}
//创建箭头节点
function createArrow() {
    var rectShape = new THREE.Shape();
    rectShape.moveTo(0, 0);
    rectShape.lineTo(10, 0);
    rectShape.lineTo(10, -30);
    rectShape.lineTo(20, -30);
    rectShape.lineTo(0, -40);
    rectShape.lineTo(-20, -30);
    rectShape.lineTo(-10, -30);
    rectShape.lineTo(-10, 0);
    rectShape.lineTo(0, 0);
    var arrowGeom = new THREE.ShapeGeometry(rectShape);
    var arrowMesh = new THREE.Mesh(arrowGeom, new THREE.MeshBasicMaterial({ color: 0x00ff00 }));
    arrowMesh.scale.set(2, 2, 2);
    arrowMesh.rotation.set(-3.14 / 2, 0, 0);
    arrowMesh.position.set(0, 10, 0);
    return arrowMesh;
}
//点击识别物体
function pickupObjects(e) {
    var raycaster = new THREE.Raycaster();
    var mouse = new THREE.Vector2();
    //将鼠标点击位置的屏幕坐标转成threejs中的标准坐标
    mouse.x = (e.clientX / window.innerWidth) * 2 - 1;
    mouse.y = -(e.clientY / window.innerHeight) * 2 + 1;
    //从相机发射一条射线，经过鼠标点击位置
    raycaster.setFromCamera(mouse, camera);
    //计算射线相机到的对象，可能有多个对象，因此返回的是一个数组，按离相机远近排列
    var intersects = raycaster.intersectObjects(scene.children, true);
    if (intersects.length > 0) {
        var obj = intersects[0].point;
        //debugger
        console.log('"x":' + obj.x.toFixed(0) + ',"y":' + obj.y.toFixed(0) + ',"z":' + obj.z.toFixed(0));
    }
    for (var i = 0; i < intersects.length; i++) {
        var inter = intersects[i].object;
//console.log(inter.name + ",pn:" + inter.parent.name);
        if (inter.parent && inter.parent.attributes) {
            //inter.material.color.set( 0x00ff00 );
            //debugger
            var attrs = inter.parent.attributes;
            var ip = attrs.ip;
            var name = attrs.name;
            cameraList.forEach(function(item) {
                 //   if (item.name === name) {
                  //      alert("ip:" + ip);
                  //  }
                })
               if (ip) {
                     //alert("ip:" + ip);
                     window.open("/bazx/app/bazx/docking/webdemo/spyl.jsp?ip="+ip);
                     break;
                 }
            var peopleId = attrs.peopleId;
            if (peopleId && moveAnimat.finish) {
                moveAnimat.model = inter.parent;
                moveAnimat.animations = attrs.animations;
                //只有停止的时候才能起启动播放
                move(attrs.roomIds);
                break;
            }
        }
    }
}
//初始化场景
function init() {
    container = document.getElementById('canvas-wrapper');
    document.body.appendChild(container);
    scene = new THREE.Scene();

    // 3D font begin..
    var loader = new THREE.FontLoader();
    loader.load('fonts/gentilis_regular.typeface.json', function(font) {
        textfontcc = font;
    });
    // 3D font end
    var ambient = new THREE.AmbientLight(0xaaaaaa);
    scene.add(ambient);

    var pointLight = new THREE.PointLight(0x999999, 0.9);
    pointLight.position.set(-2000, 1200, 0);
    scene.add(pointLight);
    renderer = new THREE.WebGLRenderer({
        // antialias: true, //是否开启反锯齿
        // precision: "highp", //着色精度选择
        alpha: true
    });
    // scene.background = new THREE.Color('#fff01');
    renderer.setPixelRatio(window.devicePixelRatio);
    renderer.setSize(window.innerWidth, window.innerHeight);
    container.appendChild(renderer.domElement);
    // renderer.setClearColor(0x000000, 0);
    // renderer.setClearColor('rgb(0,150,255)');
    // window.addEventListener('resize', onWindowResize, false);
    // container.addEventListener('mousedown', onMouseDown, false);
    // container.addEventListener('mouseup', onMouseUp, false);
    //-===================================设置包围盒===============================
    var r = "images\\";
    // // //
    // var urls = [
    //     r + "bg.png", r + "bg.png",
    //     r + "bg.png", r + "bg.png",
    //     r + "bg.png", r + "bg.png"
    // ];
    // textureCube = new THREE.CubeTextureLoader().load(urls);
    // scene.background = textureCube;


    const textureLoader = new THREE.TextureLoader();

    // 加载本地图片作为背景
    textureLoader.load(
        // 本地图片路径，假设图片在 images 文件夹下，根据实际情况修改
        'images/ba1.png',
        // 加载成功的回调函数
        function (texture) {
            // 将加载的纹理设置为场景的背景
            scene.background = texture;
        },
        // 加载过程中的回调函数，可省略
        undefined,
        // 加载失败的回调函数
        function (error) {
            console.error('加载背景图片时出错:', error);
        }
    );

    //======================================camera===========================================
    camera = new THREE.PerspectiveCamera(50, window.innerWidth / window.innerHeight, 10, 100000);
    if (!controls)
        controls = new THREE.OrbitControls(camera, renderer.domElement);
    camera.position.z = -1000;
    camera.position.y = 1000;
    //视点位置
    camera.position.copy(new THREE.Vector3(-1406.99513034711595, 1653.2753315201717, -1849.6461699292352));
    //视点朝向
    var center = new THREE.Vector3(-539.1898620614369, 24.261999951625466, 28.191516874324286);
    camera.lookAt(center);
    controls.target.copy(center);
    loadSceneModel();
    //loadGltfModel();

    moveAnimat.arrowNode = createArrow();
    var url = "./data/getDwList_gs.json";//getDwList.json";JSON
    //var url ="http://211.149.188.211:8562/trace/getDwList";
    $.getJSON(url,function(data) {
        //debugger;
        if (!data) {
            return;
        }
        if (data.scene) {
            //场景位置微调
            scene.rotation.y += data.scene.rot[1] * Math.PI;
            //scene.position.x += data.scene.pos[0];

        }
        if (data.roomList) {
            roomList = data.roomList;
        }
        if (data.actionList && data.actionList.length > 0) {
        //    actionList = data.actionList;
        //    loadJDModel();
        }
		if(data.doorList){
			doorList = data.doorList;
		}
         if (data.cameraList) {
             cameraList = data.cameraList;
             loadCameraModel();
         }
     	/**/$.ajax({
			url: "/bazx/bazx_shdw/showPerson",
			//url:"http://95.3.15.3:8180/localsense/gaojing/getallbyname?currentLoginUsername=admin&state=1",
			type: "POST",
			async:false,
			dataType: "json",
			data:{},
			success: function(data){
				if(data.list.length>0){}
				actionList = data.list;
			    loadJDModel();
			}
		});
    })
}
//加载人物模型
function loadJDModel() {
    var loader = new THREE.JDLoader();
    loader.load("models/walkingMan/walkingJD-png.jd", function(data) {
        var group = new THREE.Group();
        var matArray = data.materials; //createMaterials(data);//data.materials;
        for (var i = 0; i < data.objects.length; ++i) {
            if (data.objects[i].type == "Mesh" || data.objects[i].type == "SkinnedMesh") {
                var mesh = null;
                var mat = null;
                if (matArray.length > i) {
                    mat = matArray[i];
                }
                var color = "#fff";
                //mat.emissive = new THREE.Color(0xCB9E80);//""
                //mat =  new THREE.MeshBasicMaterial({color: 0xcccccc});
                //debugger
                if (data.objects[i].type == "SkinnedMesh") {

                    mesh = new THREE.SkinnedMesh(data.objects[i].geometry, mat);
                } else // Mesh
                {
                    mesh = new THREE.Mesh(data.objects[i].geometry, mat);
                }
                //meshes.push(mesh);
                //scene.add(mesh);
                group.add(mesh);
                //Now we need THREE.AnimationMixer to play the animation.
                // if (mesh && mesh.geometry.animations)
                // {
                //     var mixer = new THREE.AnimationMixer(mesh);
                //     mixers.push(mixer);
                //     var action = mixer.clipAction( mesh.geometry.animations[0] );
                //     action.play();
                // }
            } else if (data.objects[i].type == "Line") {
                var jd_color = data.objects[i].jd_object.color;
                var color1 = new THREE.Color(jd_color[0] / 255, jd_color[1] / 255,
                    jd_color[2] / 255);
                // var material = new THREE.LineBasicMaterial({ color: color1 });
                // var line = new THREE.Line(data.objects[i].geometry, material);
                //scene.add(line);
                group.add(mesh);
                // if (line.geometry.animations)
                // {
                //     var mixer = new THREE.AnimationMixer(line);
                //     mixers.push(mixer);
                //     var action = mixer.clipAction(line.geometry.animations[0]);
                //     action.play();
                // }
            }
        }
        group.scale.set(0.04, 0.04, 0.04);
        addPeopleModelToScene(group);
    });
}
//根据action将模型添加到场景中
function addPeopleModelToScene(model) {
    var peoIndex = 0;
    actionList.forEach(function(action, index) {
        //console.log(peoModel.id);
        //peoModel.attributes= action;
        var roomId = action.roomIds[0];
        var room = roomList[roomId];
        if (room) {
            var peoModel = null;
            if (peoIndex) {
                peoModel = model.clone();
            } else {
                peoModel = model;
            }
            var animations = [];
            for (var i = 0; i < peoModel.children.length; i++) {
                var mesh = peoModel.children[i];
                if (mesh && mesh.geometry.animations) {
                    var mixer = new THREE.AnimationMixer(mesh);
                    mixers.push(mixer);
                    var ac = mixer.clipAction(mesh.geometry.animations[0]);
                    animations.push(ac);
                }
            }
            action.animations = animations;
            peoModel.name = peoIndex;
            //peoModel.position.set(room.x,room.y,room.z);
            var textScripte = new THREE.TextSprite({
                textSize: 15,
                //redrawInterval: redrawInterval,
                material: {
                    color: 0xff0000,
                },
                texture: {
                    text: action.info,
                    fontFamily: "宋体",
                    autoRedraw: true,
                },
            });
            textScripte.position.set(0, 200, 0);
            var group = new THREE.Group();
            group.attributes = action;
            var pos = room.pos;
            group.position.set(pos.x, pos.y, pos.z);
            group.add(peoModel);
            group.add(textScripte);
            scene.add(group);
            peoIndex++;
        } else {
            alert("没找到这个房间：" + roomId);
        }
    })
}
//加载监控器模型
function loadCameraModel() {
    var onProgress = function(xhr) {
        if (xhr.lengthComputable) {
            var percentComplete = xhr.loaded / xhr.total * 100;
            ////console.log( Math.round(percentComplete, 2) + '% downloaded' );
        }
    };
    var onError = function(xhr) {};
    var dir = "models/cam/";
    var fileName = "cam";
    var mtlLoader = new THREE.MTLLoader();
    mtlLoader.setPath(dir);
    mtlLoader.load(fileName + '.mtl', function(materials) {
        materials.preload();
        var objLoader = new THREE.OBJLoader();
        objLoader.setMaterials(materials);
        objLoader.setPath(dir);
        objLoader.load(fileName + '.obj', function(object) {
            var scalev = 0.1;
            object.scale.set(scalev, scalev, scalev);
            if (object instanceof THREE.Group) {
                object.traverse(function(child) {
                    if (child instanceof THREE.Mesh) {
                        //child.material.color.setHex( 0xdfdfdf );
                        //child.material.side = THREE.DoubleSide;
                        //child.material["transparent"] = true;
                        //child.material["depthWrite"] = false;
                        //child.material.color = new THREE.Color(0x000000);
                    }
                });
            }
            //cameraModel = object;
            addCameras(object);
            //不需要添加和摄像头了
        }, onProgress, onError);

    });
}
//加载场景模型
function loadSceneModel() {
    var objfolder = "models/gansuPolice/";
    var fileprefix = "banan";
    var onProgress = function(xhr) {
        if (xhr.lengthComputable) {
            var percentComplete = xhr.loaded / xhr.total * 100;
            ////console.log( Math.round(percentComplete, 2) + '% downloaded' );
        }
    };
    var onError = function(xhr) {};
    THREE.Loader.Handlers.add(/\.dds$/i, new THREE.DDSLoader());
    var mtlLoader = new THREE.MTLLoader();
    mtlLoader.setPath(objfolder);
    mtlLoader.load(fileprefix + '.mtl', function(materials) {
        materials.preload();
        var objLoader = new THREE.OBJLoader();
        objLoader.setMaterials(materials);
        objLoader.setPath(objfolder);
        objLoader.load(fileprefix + '.obj', function(object) {
            var scalev = 2.7;
			object.position.x-=500;

            object.scale.set(scalev, scalev, scalev);
            scene.add(object);
        }, onProgress, onError);

    });

}

function loadGltfModel() {
    var loader = new THREE.GLTFLoader();

    // Optional: Provide a DRACOLoader instance to decode compressed mesh data
    //THREE.DRACOLoader.setDecoderPath( '/js/libs/draco' );
    //loader.setDRACOLoader( new THREE.DRACOLoader() );

    // Load a glTF resource
    loader.load(
        // resource URL
        'models/zspcs2/police.gltf',
        // called when the resource is loaded
        function(gltf) {
            var scalev = 0.1;
            //debugger
            gltf.scene.scale.set(scalev, scalev, scalev);

            scene.add(gltf.scene);
            gltf.animations; // Array<THREE.AnimationClip>
            gltf.scene; // THREE.Scene
            gltf.scenes; // Array<THREE.Scene>
            gltf.cameras; // Array<THREE.Camera>
            gltf.asset; // Object

        },
        // called while loading is progressing
        function(xhr) {

            console.log((xhr.loaded / xhr.total * 100) + '% loaded');

        },
        // called when loading has errors
        function(error) {

            console.log('An error happened');

        }
    );
}
//鼠标按下
function onMouseDown(event) {
    // nowpeopletypeid = (nowpeopletypeid + 1) % peoplelist.length;
    // nowpeoplestandroomid = (nowpeoplestandroomid + 1) % 19;
    // setshowpos(nowpeopletypeid, nowpeoplestandroomid);

}
//鼠标弹起
function onMouseUp(evt) {
    pickupObjects(event);
}
//渲染场景
function animate() {
    if (controls) controls.update();
    if (camera) renderer.render(scene, camera);
    requestAnimationFrame(animate);
    playMove();
    if (!moveAnimat.finish && mixers.length > 0) {
        var delate = clock.getDelta();
        for (var i = 0; i < mixers.length; i++) {
            mixers[i].update(delate);
        }
    }
}
//点击后计算人物模型移动轨迹
function move(roomIds) {
    //如果只有1个房间不移动
    if (roomIds.length < 2) {
        alert("只有一个房间");
        return;
    }
    for (var i in moveAnimat.animations) {
        var animation = moveAnimat.animations[i];
        animation.play();
    }

    var material = new THREE.LineBasicMaterial({
        color: 0x0000ff,
        linewidth: 8 //由于受限于 角度层（ANGLE layer），在Windows平台上使用 WebGL，线宽将总是为1而不管设置的值
    });
    //先清空路径
    moveAnimat.path = [];
    var geometry = new THREE.Geometry();
	console.log(roomIds);
    for (var index = 0; index < roomIds.length - 1; index++) {
        var posArr = [];
        var spos = roomList[roomIds[index]].pos;
        var epos = roomList[roomIds[index + 1]].pos;
        //var doorPos = roomList[roomIds[index]].door;
        //var doorPos2 = roomList[roomIds[index + 1]].door;
		var doorPos = getDoorPos(roomIds[index],roomIds[index+1]);
		var doorPos2 = doorPos;
        if (spos && epos) {
            var sposx = parseFloat(spos.x);
            var sposy = parseFloat(spos.y);
            var sposz = parseFloat(spos.z);
            var eposx = parseFloat(epos.x);
            var eposy = parseFloat(epos.y);
            var eposz = parseFloat(epos.z);
            if (roomIds[index] === "ZL") {
                //计算走廊位置z
                var z = doorPos2.z;
				var x = doorPos2.x;
                var lastV = 0;
                if (geometry.vertices.length > 0) {
					var perPos = geometry.vertices[geometry.vertices.length - 1];
					if(perPos)
						lastV = zlVec[0]?perPos.x:perPos.z;
                }
                var dis =zlVec[0]?Math.abs(lastV - x):Math.abs(lastV - z);
                if (dis > 50&&doorPos2) {
                    //不在对面的话，要加，根据走廊的方向决定加入走廊的那个分量
                    posArr.push(
                        new THREE.Vector3(zlVec[0]? parseFloat(doorPos2.x):sposx, sposy, zlVec[0]?sposz:parseFloat(doorPos2.z))
                    );
                }

            } else {
                //加入起点
                posArr.push(
                    new THREE.Vector3(sposx, sposy, sposz)
                );
            }

            if (roomIds[index + 1] === "ZL") {
                //如果要经过走廊，先出门，加入门位置
                posArr.push(
                    new THREE.Vector3(parseFloat(doorPos.x), sposy, parseFloat(doorPos.z))
                );

                posArr.push(
                    new THREE.Vector3(zlVec[0]?parseFloat(doorPos.x):eposx, eposy, zlVec[0]?eposz:parseFloat(doorPos.z))
                );

            } else if(doorPos2){
                //如果是房间，要先进门
                posArr.push(
                    new THREE.Vector3(parseFloat(doorPos2.x), eposy, parseFloat(doorPos2.z))
                );
                //最后加入终点
                posArr.push(
                    new THREE.Vector3(eposx, eposy, eposz)
                );
            }
            posArr.forEach(function(item) {
                geometry.vertices.push(item);
                moveAnimat.path.push({ x: item.x, y: item.y, z: item.z });

            })
			console.log(posArr);
        } else {
            if (!spos) {
                alert("房间不存在：" + roomIds[index]);
            } else {
                alert("房间不存在：" + roomIds[index + 1]);
            }
            moveAnimat.path.length = 0;
            return;

        }
        //console.log(spos);
        //console.log(epos)

    }
    //插入最后一个点
    if (roomIds.length < 2) {
        var epos = roomList[roomIds[roomIds.length - 1]].pos;
        //geometry.vertices.push(new THREE.Vector3( epos.x, epos.y, epos.z ));
        moveAnimat.path.push({ x: parseFloat(epos.x), y: parseFloat(epos.y), z: parseFloat(epos.z) });
    }

    var line = new THREE.Line(geometry, material);
    scene.remove(moveAnimat.pathNode);
    moveAnimat.pathNode = line;
    scene.add(line);
    var spos = roomList[roomIds[0]].pos;
    //拷贝数据防止篡改原始数据
    moveAnimat.curPos = {};
    for (var i in spos) {
        if (i === "x" || i === "y" || i === "z") {
            moveAnimat.curPos[i] = parseFloat(spos[i]);
        } else {
            moveAnimat.curPos[i] = spos[i];
        }
    }
    moveAnimat.model.add(moveAnimat.arrowNode);
    moveAnimat.endPos = epos;
    moveAnimat.finish = false;
    moveAnimat.curIndex = 0;
    moveAnimat.direction = new THREE.Vector3(0, 0, 1);
}
//根据房间获取门的位置
function getDoorPos(room1,room2){
	var pos = null;
	if(doorList&&doorList.length>0){
		for(var i in doorList){
			var door = doorList[i];
			if(door.name.indexOf(room1)>=0&&door.name.indexOf(room2)>=0){
				pos = door.pos;
				break;
			}
		}
	}
	return pos;
}
//移动位置
function playMove() {
    if (!moveAnimat.finish) {
        //目标点

        var curPos = moveAnimat.path[moveAnimat.curIndex];
        var tarPos = moveAnimat.path[moveAnimat.curIndex + 1];
        var pathLen = (tarPos.x - curPos.x) * (tarPos.x - curPos.x) + (tarPos.z - curPos.z) * (tarPos.z - curPos.z);
        pathLen = Math.sqrt(pathLen);
        if (pathLen === 0) {
            pathLen = 1;
            //原地转弯直接下一步
            moveAnimat.curIndex++;
        }
        var datX = (tarPos.x - curPos.x) / pathLen * moveAnimat.speed;
        var datZ = (tarPos.z - curPos.z) / pathLen * moveAnimat.speed;
        moveAnimat.curPos.x += datX;
        moveAnimat.curPos.z += datZ;
        var dir = new THREE.Vector3(datX, 0, datZ);
        var ang = moveAnimat.direction.angleTo(dir) || 0;
        var cor = new THREE.Vector3(0, 0, 0);
        cor.crossVectors(moveAnimat.direction, dir);
        if (cor.y < 0) {
            ang *= -1;
        }
        var tarPos1 = moveAnimat.curPos;
        var curLen = (tarPos1.x - curPos.x) * (tarPos1.x - curPos.x) + (tarPos1.z - curPos.z) * (tarPos1.z - curPos.z);
        curLen = Math.sqrt(curLen);
        if (curLen > pathLen) {
            moveAnimat.curIndex++;
            moveAnimat.curPos.x = parseFloat(moveAnimat.path[moveAnimat.curIndex].x);
            moveAnimat.curPos.y = parseFloat(moveAnimat.path[moveAnimat.curIndex].y);
            moveAnimat.curPos.z = parseFloat(moveAnimat.path[moveAnimat.curIndex].z);
            if (moveAnimat.curIndex === moveAnimat.path.length - 1) {
                moveAnimat.finish = true;
                for (var i in moveAnimat.animations) {
                    var animation = moveAnimat.animations[i];
                    animation.stop();
                }
                moveAnimat.animations = null;
                moveAnimat.curIndex = 0;
                moveAnimat.path = [];
                moveAnimat.model.remove(moveAnimat.arrowNode);
            }
        }
        moveAnimat.model.rotation.set(0, ang, 0); //moveAnimat.model.position.y +
        moveAnimat.model.position.set(moveAnimat.curPos.x, moveAnimat.curPos.y, moveAnimat.curPos.z);


    }
}

function onWindowResize() {
    if (camera) {
        camera.aspect = window.innerWidth / window.innerHeight;
        camera.updateProjectionMatrix();
    }
    renderer.setSize(window.innerWidth, window.innerHeight);
}
init();
animate();
